import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import { userLogin } from "../../api/user.js";
import router from "../../router";
import { getInfo } from '@/api/user.js'
// 导入auth方法
import { getToken, setToken, removeToken } from '@/utils/auth';
// 导入静态路由，动态路由
import { constantRouter } from '../../router';

const useUserStore = defineStore('user', {
	state: () => {
		return {
			UserInfo: {},
			token: getToken() || "",
			isCollapse: false,
			routes: [...constantRouter],
			addRoutes: [],
			username: ''
		}
	},
	persist: {
		// 自定义持久化方式
		storage: window.localStorage,
		afterRestore: (context) => {
			context.store.UserInfo = {};
			context.store.routes = [...constantRouter];
		},
	},
	actions: {
		// 登录
		async login (userInfo) {
			try {
				const res = await userLogin(userInfo)
				setToken(res.token);
				this.token = res.token
				await router.replace("/")
				ElMessage({
					message: "登录成功",
					type: "success",
				});
			} catch (err) { }
		},
		// 退出事件
		Logout () {
			this.token = '';
			removeToken();
			this.addRoutes = [];
			this.routes = [...constantRouter];
			this.UserInfo = {};
		},
		// getUserInfo
		async getUserInfo () {
			const res = await getInfo();
			const info = {
				id: 1,
				...res,
			};
			this.UserInfo = info;
		},
		// 改变菜单收缩
		changeIsCollapse (str) {
			this.isCollapse = str
		},
	},
	getters: {},
})

export default useUserStore